package smartKiwi;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
import java.util.Properties;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class SmartKiwiRequest {

	private Properties props;



	public SmartKiwiRequest(Properties _props) {
		props = _props;
	}


	public SmartKiwiRequest(String _url, String _username, String _password) {
		props = new Properties();
		props.setProperty("login", _username);
		props.setProperty("password", _password);
		props.setProperty("URL", _url);
	}

	public int login() {
		try {
			String loginUrl = props.getProperty("URL") + "?j_username=" + props.getProperty("login") + "&j_password="
					+ props.getProperty("password");
			URL obj = new URL(loginUrl);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET");

			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'GET' request to URL : " + loginUrl);
			System.out.println("Response Code : " + responseCode);
			return 1;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return -1;

	}

	public String getFiches() {
		try {
			String loginUrl = props.getProperty("URL") + "fiches/?j_username=" + props.getProperty("login")
					+ "&j_password=" + props.getProperty("password");
			URL obj = new URL(loginUrl);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET");

			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'GET' request to URL : " + loginUrl);
			System.out.println("Response Code : " + responseCode);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// print result
			System.out.println("getFiches Response :" + response.toString());
			return response.toString();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;

	}

	public String getRepertoiresOfFiche(int idFiche) {
		try {
			String loginUrl = props.getProperty("URL") + "repertoires/" + idFiche + "/?j_username="
					+ props.getProperty("login") + "&j_password=" + props.getProperty("password");
			URL obj = new URL(loginUrl);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET");

			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'GET' request to URL : " + loginUrl);
			System.out.println("Response Code : " + responseCode);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// print result
			System.out.println("getRepertoiresOfFiche Response :"
					+ response.toString());
			return response.toString();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;

	}

	public boolean envoyerTexte(String str_fiche) {
		try {
			String loginUrl = props.getProperty("URL") + "envoyerTexte/?j_username=" + props.getProperty("login")
					+ "&j_password=" + props.getProperty("password");
			URL obj = new URL(loginUrl);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setRequestProperty("content-type", "application/json");

			OutputStreamWriter out = new OutputStreamWriter(
					con.getOutputStream());
			out.write(str_fiche);
			out.flush();
			out.close();

			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'POST' request to URL : " + loginUrl);
			System.out.println(" texte Response Code : " + responseCode);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			JSONParser jsonParser = new JSONParser();
            JSONObject requestReturn = (JSONObject) jsonParser.parse(response.toString());
            if(response.toString().contains("[") && response.toString().contains("]"))
            {
            	JSONArray messages = (JSONArray)requestReturn.get("modeleRetourEnvoyerTexte");
            	for(int i=0;i<messages.size();i++)
                {
                	JSONObject message = (JSONObject)messages.get(i); 
                	SmartKiwiRequestHMI popUp = new SmartKiwiRequestHMI(message,i);
                	popUp.setVisible(true);	
                }
            }
            else
            {
            	JSONObject message = (JSONObject) requestReturn.get("modeleRetourEnvoyerTexte");
            	SmartKiwiRequestHMI popUp = new SmartKiwiRequestHMI(message,0);
            	popUp.setVisible(true);
            }
            
			// print result
			System.out.println("envoyerDocument Response :"
					+ response.toString());
			return true;
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return false;
	}

	public boolean envoyerDocument(String jsonDocument) {
		try {
			String loginUrl = props.getProperty("URL") + "envoyerDocument/?j_username=" + props.getProperty("login")
					+ "&j_password=" + props.getProperty("password");
			URL obj = new URL(loginUrl);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setRequestProperty("content-type", "application/json");

			OutputStreamWriter out = new OutputStreamWriter(
					con.getOutputStream());
			out.write(jsonDocument);
			out.flush();
			out.close();
			


			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'POST' request to URL : " + loginUrl);
			System.out.println("Response Code : " + responseCode);
			
			

			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			
			JSONParser jsonParser = new JSONParser();
            JSONArray messages = (JSONArray) jsonParser.parse(response.toString());
            for(int i=0;i<messages.size();i++)
            {
            	JSONObject message = (JSONObject)messages.get(i); 
            	SmartKiwiRequestHMI popUp = new SmartKiwiRequestHMI(message,i);
            	popUp.setVisible(true);	
            }
			
			// print result
			System.out.println("envoyerDocument Response :"
					+ response.toString());
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return false;
	}

}
